package com.linjiahao.netty.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @ClassName WebSockerHandler
 * @Description: 自定义业务handler
 * @Author linjiahao
 * @Date 23/12/2021
 **/
@Component
@Slf4j
@ChannelHandler.Sharable
public class WebSockerHandler extends SimpleChannelInboundHandler<Object> {

    @Autowired
    private WebSocketAuthHttpHanlder authHttpHanlder;

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        log.info("与客户端建立连接，通道开启,id:{}", ctx.channel().id());
        ChannelHandlerPool.channelGroup.add(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        log.info("与客户端断开连接，通道关闭,id:{}", ctx.channel().id());
        ChannelHandlerPool.channelGroup.remove(ctx.channel());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object message) {
        if (message instanceof FullHttpRequest){
            //以http请求形式接入，但是走的是websocket,首次需要鉴权
            authHttpHanlder.authHandler(ctx, (FullHttpRequest) message);
            log.info("鉴权完成");
        }else if (message instanceof TextWebSocketFrame){
            //处理websocket客户端的消息
            
        }

    }


}
